package com.tony.inet;

import jdk.jfr.events.SocketReadEvent;

import java.io.*;
import java.net.*;
import java.util.Scanner;

/**
 * @version V1.0  </br>
 * @ClassName UDPSendReceive </br>
 * @Description TODO  </br>
 * @Author tonywang</br>
 * @DATE 2/26/2019 1:52 PM</br>
 */
public class TCPSendReceive {
    public static void main(String[] args) throws IOException {
//        TCPReceive.runTCPReceive();
//        TCPSend.runTCPSend();
    }
}

class TCPSend{
    public static void runTCPSend() throws IOException {
        //创建客户端socket服务。
        Socket socket = new Socket("localhost",10001);
        //获取socket流中的输出流。
        Scanner cin = new Scanner(System.in);
        while (true) {
            System.out.println("enter word:");
            String text = cin.nextLine();
            OutputStream outputStream = socket.getOutputStream();
            //使用输出流将指定的数据写出去。
            System.out.println("send message:" + text);
            outputStream.write(text.getBytes());
            if (text.equals("886")) {
                // 关闭资源
                outputStream.close();
            }
        }

    }
}

class TCPReceive{
    public static void runTCPReceive() throws IOException {
        //1，创建服务端socket服务。通过ServerSocket对象。
        //2，服务端必须对外提供一个端口，否则客户端无法连接。
        ServerSocket serverSocket = new ServerSocket(10001);
        System.out.println("start server");
        //3，获取连接过来的客户端对象。
        Socket client = serverSocket.accept();
        String ip = client.getInetAddress().getHostAddress();
        String name = client.getInetAddress().getCanonicalHostName();
        System.out.println("connect success, ip: " + ip + " name: " + name);
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(client.getInputStream()));
        String text = null;
        //4，通过客户端对象获取socket流读取客户端发来的数据 并打印在控制台上。
        while (true) {
            text = bufferedReader.readLine();
            if (text != null) {
                System.out.println(ip + ":" + text);
            }
            //5，关闭资源。关客户端，关服务端。
            if ("886".equals(text)) {
                System.out.println("退出聊天窗口");
                client.close();
                serverSocket.close();
            }
        }
    }
}